package com.sz.ruichar.controller.beans;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.sz.ruichar.entity.model.constant.Constant;
import com.sz.ruichar.entity.model.constant.MsgException;
import com.sz.ruichar.entity.model.wechat.param.SignatureBean;
import com.sz.ruichar.service.entity.model.result.ResultData;
import com.sz.ruichar.service.wechat.WeixinService;
import com.sz.ruichar.utils.system.SignUtil;
import com.sz.ruichar.utils.system.wechat.AccessTokenUtil;
import com.sz.ruichar.utils.system.wechat.WechatHttpUtils;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.common.util.RandomUtils;
import me.chanjar.weixin.common.util.crypto.SHA1;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
//[wechat-Frame]https://www.w3cschool.cn/wxtools/wxtools-ozc822fy.html
@RestController
@RequestMapping("/wechat")
public class WechatCoreController 
{
    private static Logger log = LoggerFactory.getLogger(WechatCoreController.class);
    @Autowired
    private WeixinService wxService;
    @Value("${appId_wechat}")
    private String appIdWechat;
    @Value("${appSecret_wechat}")
    private String appSecretWechat;
    @Value("${token_wechat}")
    private String tokenWechat;
    @Value("${aesKey_wechat}")
    private String aesKeyWechat;
//    @Value("${redirect_url}")
//    private String redirectUrlWechat;
    //验证是否来自微信服务器的消息
    @RequestMapping(value = "/checkConfig")
    public String checkSignature(HttpServletRequest request,@RequestBody String xml)
    {
    	log.info("=====start wechat service====");
    	if("get".equalsIgnoreCase(request.getMethod()))
        {
			String signature = request.getParameter("signature");
	        String timestamp = request.getParameter("timestamp");
	        String nonce = request.getParameter("nonce");
	        String echostr = request.getParameter("echostr");
	        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
	        if (SignUtil.checkSignature(signature, timestamp, nonce)) 
	        {
	            log.info("=======wechat接入成功=========");
	            return echostr;
	        }
	        else
	        {
	        	log.error("=======wechat接入失败===signature={},timestamp={},nonce={},echostr={}==",
	        			signature,timestamp,nonce,echostr);
	        	return "";
	        }
        }
        else
        {
        	log.info("======xml={}",xml);
        	// 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(xml);
            WxMpXmlOutMessage outMessage = this.wxService.route(inMessage);
            if (outMessage == null) 
            {
            	return "";
            }
            else
            {
            	return outMessage.toXml();
            }
           
        }
        
    }
    
    @PostMapping(value = "/getOpenId")
    public ResultData getOpenId(@RequestBody Map<String, String> map)
    {
    	try
    	{
    		log.info("=======paramMap={}",map);
    		String code = map.get("code");
    		if(StringUtils.isEmpty(code))
    		{
    			throw new MsgException("参数错误");
    		}
//    		String token = AccessTokenUtil.getAccessToken(appIdWechat, appSecretWechat);
    		String getAccessTokenUrl = Constant.WECHAT_AUTH_ACCESS_TOKEN_URL.replace("APPID",appIdWechat).
    				replace("SECRET", appSecretWechat).replace("CODE", code);
    		log.info("====getAccessTokenUrl =={}==",getAccessTokenUrl);
    		String json = WechatHttpUtils.doGet(getAccessTokenUrl);
    		log.info("===authAccessToken======json={}",json);
    		String openId = JSONObject.parseObject(json).getString("openid");
    		log.info("===openId={}",openId);
    		return ResultData.success(openId);
    	}
    	catch(MsgException e)
    	{
    		return ResultData.error(e.getMessage());
    	}
    	catch(Exception e)
    	{
    		return ResultData.error();
    	}
  }
    
    
    /**
     * @param map
     * @return
     * 获取分享的sing
     */
    @GetMapping(value = "/getShareSing")
    public ResultData getShareSing( HttpServletRequest request)
    {
    	try
    	{
    		String nonceStr = RandomUtils.getRandomStr();
    		String timeStamp = (new Date().getTime()/1000)+"";
    		String jsApiTicket = wxService.getJsapiTicket(false);
    		String url = URLDecoder.decode(request.getParameter("url"));  
    		StringBuilder sbl = new StringBuilder();
    		sbl.append("jsapi_ticket=").append(jsApiTicket).append("&")
    		.append("noncestr=").append(nonceStr).append("&")
    		.append("timestamp=").append(timeStamp).append("&")
    		.append("url=").append(url);
    		String signature =   SHA1.genWithAmple(sbl.toString());
    		log.info("======varURL={},sign={}",sbl.toString(),signature);
            SignatureBean signatureBean = new SignatureBean();  
            signatureBean.setNoncestr(nonceStr);  
            signatureBean.setSignature(signature);
            signatureBean.setTimestamp(timeStamp);
            signatureBean.setUrl(url); 
    		return ResultData.success(signatureBean);
    	}
    	catch(Exception e)
    	{
    		log.error("======error:{}",e);
    		return ResultData.error();
    	}
  }
    
//    /**
//     * @param request
//     * 获取openID之前先获取code
//     */
//    由界面完成
//    @GetMapping(value = "/getCode")
//    public void getCode(HttpServletRequest request)
//    {
//    	try 
//    	{
//			String getCodeUrl = Constant.WEHCAT_CODE_URL.replace("APPID", appIdWechat).
//					replace("REDIRECT_URI", URLEncoder.encode(redirectUrlWechat,"UTF-8"))
//					.replace("SCOPE", "snsapi_base");
//			log.info("====getCode url=={}==",getCodeUrl);
//			WechatHttpUtils.doGet(getCodeUrl);
//		} 
//    	catch (Exception e) 
//    	{
//			log.error("==========ex:{}",e);
//		}
//    }
//    
//    /**
//     * @param request
//     * @param response
//     * @return
//     * 获取accessToken,openId
//     */
//    @RequestMapping(value = "/getAuthAccessToken",method = RequestMethod.GET)
//    public String getAuthAccessToken(HttpServletRequest request,HttpServletRequest response)
//    {
//    	try 
//    	{
//    		String code = request.getParameter("code");
//    		String getAccessTokenUrl = Constant.WECHAT_AUTH_ACCESS_TOKEN_URL.replace("APPID", WxConfig.getInstance().getAppId()).
//    				replace("SECRET", WxConfig.getInstance().getAppSecret()).replace("CODE", code);
//    		log.info("====getAccessTokenUrl =={}==",getAccessTokenUrl);
//    		String json = WechatHttpUtils.doGet(getAccessTokenUrl);
//    		log.info("===authAccessToken======json={}",json);
//    	} 
//    	catch (Exception e) 
//    	{
//    		log.error("==========ex:{}",e);
//    	}
//    	return "";
//    }
    
    @RequestMapping(value = "/createMenu",method = RequestMethod.POST)
    public String createMenu()
    {
    	try 
    	{
    		log.info("===========execute createMenu====");
    		WxMenu menu = new WxMenu();
    		WxMenuButton button1 = new WxMenuButton();
    		button1.setType(WxConsts.BUTTON_VIEW);
    		button1.setName("豆子互娱");
    		button1.setUrl("http://5beans.cn/wechatMP/mall/?from=groupmessage&isappinstalled=0#/main");
    		WxMenuButton button2 = new WxMenuButton();
    		button2.setName("红包领取");
    		button2.setType(WxConsts.BUTTON_CLICK);
    		button2.setKey("你好欢迎来到五颗小豆^_^，复制此消息，打开最新版支付宝就能领取！9zRFMU58X2");
//    		button2.set
    		menu.getButtons().add(button1);
    		menu.getButtons().add(button2);
//            WxMenuButton button3 = new WxMenuButton();
//            button3.setName("菜单");
//            menu.getButtons().add(button3);
//
//            WxMenuButton button31 = new WxMenuButton();
//            button31.setType(WxConsts.BUTTON_VIEW);
//            button31.setName("豆子互娱");
//            button31.setUrl("http://5beans.cn/wechatMP/mall/?from=groupmessage&isappinstalled=0#/main");
//
//            WxMenuButton button32 = new WxMenuButton();
//            button32.setType(WxConsts.BUTTON_VIEW);
//            button32.setName("视频");
//            button32.setUrl("http://v.qq.com/");
//
//            WxMenuButton button33 = new WxMenuButton();
//            button33.setType(WxConsts.BUTTON_CLICK);
//            button33.setName("赞一下我们");
//            button33.setKey("V1001_GOOD");
//
//            button3.getSubButtons().add(button31);
//            button3.getSubButtons().add(button32);
//            button3.getSubButtons().add(button33);
    		String result = this.wxService.getMenuService().menuCreate(menu);
    		log.info("====create menu==result={}===",result);
    	} 
    	catch (Exception e) 
    	{
    		log.error("==========ex:{}",e);
    	}
    	return "success";
    }
    
    
    
}
